package com.gywj.race.controller.api;

import com.gywj.race.config.result.AjaxResultHandler;
import com.gywj.race.util.verify.code.RandomValidateCodeUtil;
import com.gywj.race.dto.LoginDto;
import com.gywj.race.entity.Employees;
import com.gywj.race.service.EmployeeService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class LoginController {
    @Resource
    private EmployeeService employeeService;

    @GetMapping("/login/page")
    public ModelAndView loginPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login-1");
        return modelAndView;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody @Validated LoginDto loginDto, HttpServletRequest request) {
        try {
            if (!this.checkVerify(loginDto.getCaptcha(), request.getSession())) {
                return AjaxResultHandler.Failed("错误的验证码");
            }
            Employees loginEmployee = employeeService.login(loginDto.getUsername(), loginDto.getPassword());
            //登陆成功加session
            request.getSession().setAttribute("employee", loginEmployee);
            request.getSession().setMaxInactiveInterval(30*60);
            return AjaxResultHandler.Success("成功", loginEmployee);
        } catch (Exception e) {
            return AjaxResultHandler.Failed(e.getMessage());
        }
    }

    @PostMapping("/loginOut")
    public Map<String, Object> loginOut(HttpServletRequest request) {
            try {
                //退出清除 session
                request.getSession().removeAttribute("employee");
                return AjaxResultHandler.Success();
            } catch (Exception e) {
                return AjaxResultHandler.Failed(e.getMessage());
            }
         }


    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private boolean checkVerify(String code, HttpSession session) {
        try {
            //从session中获取随机数
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                return false;
            }
            if (random.equals(code)) {
                System.out.println("正确的验证码");
                return true;
            }
            System.out.println("错误的验证码");
            return false;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}
